<template>
	<fui-form>
		<fui-input required label="手机号" placeholder="请输入手机号码" v-model="formData.phone"></fui-input>
		<fui-input required :padding="['20rpx','32rpx']" label="验证码" placeholder="请输入手机验证码" v-model="formData.smsCode">
			<fui-countdown-verify background="#0052D9" color="#fff" @send="sendCode"
				ref="fui_cdv"></fui-countdown-verify>
		</fui-input>
		<view class="fui-btn__box">
			<fui-button bold @click="submit">
				登陆
			</fui-button>
		</view>

	</fui-form>
</template>

<script>
	import {
		AuthApi
	} from '../../api/login'
	import {
		mapActions,
		mapState
	} from 'pinia'
	import form from '@/components/firstui/fui-validator/fui-validator'
	import {
		useAuthStore
	} from '../../store/modules/auth'
	import {
		MainPages
	} from '../../config/router-config'
	import {
		WX_APPID
	} from '../../_env'
	import {
		isWechat
	} from "../../utils/wechat";
	import _ from 'lodash'
	import {
		useWx
	} from '../../store/modules/wx'
	export default {
		data() {
			return {
				formData: {
					/**
					 * 微信用户code
					 */
					openid: '',
					key: '',
					/**
					 * 手机号
					 */
					phone: '',
					/**
					 * 短信验证码
					 */
					smsCode: '',
				}
			}
		},
		computed: {
			...mapState(useAuthStore, ['authInfo']),
		},
		onLoad(options) {
			this.setIosUrl()
			if (isWechat()) {
				let code = this.getUrlCode('code')
				if (code) {
					this.login(code)
				} else {
					this.auth()
				}
			}

		},
		methods: {
			...mapActions(useAuthStore, ['setAuthInfo', 'setToken']),
			...mapActions(useWx, ['setIosUrl']),
			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location
					.href) || [, ''])[1].replace(/\+/g, '%20')) || null
			},
			async login(code) {
				try {
					const res = await AuthApi.getOpenId(code)
					this.setAuthInfo(res.data)
					const l = await AuthApi.login({
						openid: res.data.openid
					})
					if (l.code === 401) {
						uni.showModal({
							title: '提示',
							content: '账户未绑定',
							showCancel: false,
							success() {

							}

						})

					} else {
						this.setToken(l.data)
						uni.showToast({
							icon: 'success',
							title: '登录成功',
						})
						_.delay(() => {
							uni.hideToast()
							uni.redirectTo({
								url: `${MainPages.Index.router}`
							})
						}, 1000)

					}

				} catch (err) {
					this.fui.toast(err)
				}
			},
			auth() {
				if (!this.authInfo) {
					let local = encodeURIComponent(window.location.href)
					let appid = WX_APPID;
					const href = `
					https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${local}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
					`
					window.location.href = href
				}

			},
			async submit() {
				if (!this.authInfo) {
					this.fui.toast('未检测到授权信息')
					return
				}
				this.formData.openid = this.authInfo.openid
				const res = form.validator(this.formData, [{
					name: 'phone',
					rule: ["required", 'isMobile'],
					msg: ["请输入手机号", "请输入正确的手机号"]
				}, {
					name: 'smsCode',
					rule: ["required", ],
					msg: ["请输入验证码"]
				}])
				if (res.isPassed) {
					try {
						const res = await AuthApi.login(this.formData)
						this.setToken(res.data)
						uni.redirectTo({
							url: MainPages.Index.router
						})
					} catch (e) {
						uni.showModal({
							showCancel: false,
							title: '提示',
							content: e
						})
					}
				} else {
					this.fui.toast(res.errorMsg)
				}
			},
			async sendCode() {
				const res = form.validator(this.formData, [{
					name: 'phone',
					rule: ["required", 'isMobile'],
					msg: ["请输入手机号", "请输入正确的手机号"]
				}])
				if (res.isPassed) {
					try {
						const res = await AuthApi.getCode()
						this.formData.key = res.data
						this.$refs.fui_cdv && this.$refs.fui_cdv.success()
					} catch (e) {
						this.fui.toast(e)
						this.$refs.fui_cdv && this.$refs.fui_cdv.reset()
						//TODO handle the exception
					}
				} else {
					this.fui.toast(res.errorMsg)
					this.$refs.fui_cdv && this.$refs.fui_cdv.reset()
				}
			},

		}
	}
</script>

<style>

</style>